package com.md.facade;

import com.md.api.LoginApi;
import com.md.model.system.CommonResult;
import com.md.request.AzureSamlLoginRequest;
import com.md.request.LoginRequest;
import com.md.util.SamlUtil;
import org.opensaml.saml.saml2.core.AuthnRequest;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Base64;

public class LoginController implements LoginApi {
  @Override
  public CommonResult<Void> azureSaml(final AzureSamlLoginRequest request) {
//    List<AzureSamlConfig> analysis = AzureSamlCoreConfiguration.analysis("https://login.microsoftonline.com/00618cc4-0e79-43ef-9df6-41ddc9a38d62/federationmetadata/2007-06/federationmetadata.xml?appid=a2c39ba2-3cc0-4a44-acaa-20b96dc35ebd");
    List<AzureSamlConfig> analysis = AzureSamlCoreConfiguration.analysis("RDIC-DEV.xml");
    AzureSamlConfig azureSamlConfig = analysis.get(0);
    AuthnRequest authnRequest = SamlUtil.createRequest(azureSamlConfig);
    authnRequest.setAssertionConsumerServiceURL("http://localhost:8090/saml/callback/");
//    authnRequest.setAssertionConsumerServiceURL("https://3s35r49356.oicp.vip/users/response");

    String s = Base64.getEncoder().encodeToString(samlDeflate(SamlUtil.serialize(authnRequest)));
    UriComponentsBuilder uriBuilder = UriComponentsBuilder
      .fromUriString(azureSamlConfig.getSignOnServiceBinding().getUrl());
    addParameter("SAMLRequest", s, uriBuilder);
    // 此处应记录一个登录记录,用于回调的时候拿到对应的请求信息
    addParameter("RelayState", "NOUST123", uriBuilder);
    addParameter("SigAlg", null, uriBuilder);
    addParameter("Signature", null, uriBuilder);
    return CommonResult.success(AzureSamlLoginResponse.builder().url(uriBuilder.build(true).toUriString()).build());
    return null;
  }

  @Override
  public CommonResult<Void> login(final LoginRequest request) {
    return null;
  }
}
